<template>
  <div class="create-order-container">
    <div class="header">
      <button class="back-btn" @click="goBack">←</button>
      <span class="title">创建订单</span>
      <button class="test-btn" @click="testRabbitMQ">测试连接</button>
    </div>

    <!-- RabbitMQ状态指示器 -->
    <div class="status-indicator" :class="{ 'connected': rabbitMQConnected, 'disconnected': !rabbitMQConnected }">
      <div class="status-dot"></div>
      <span>{{ rabbitMQConnected ? 'RabbitMQ已连接' : 'RabbitMQ未连接' }}</span>
    </div>

    <!-- 收货地址 -->
    <div class="address-section">
      <div class="section-title">收货地址</div>
      <div class="address-card" @click="editAddress">
        <div class="address-info">
          <div class="name-phone">
            <span class="name">{{ address.name || '请填写收货人' }}</span>
            <span class="phone">{{ address.phone || '' }}</span>
          </div>
          <div class="detail">{{ address.detail || '请填写详细地址' }}</div>
        </div>
        <div class="arrow">></div>
      </div>
    </div>

    <!-- 商品选择 -->
    <div class="goods-section">
      <div class="section-title">选择商品</div>
      <div class="goods-list">
        <div 
          v-for="goods in availableGoods" 
          :key="goods.id"
          class="goods-item"
          :class="{ 'selected': selectedGoods.some(g => g.id === goods.id) }"
          @click="toggleGoods(goods)"
        >
          <img :src="goods.image_url" :alt="goods.name" class="goods-image" />
          <div class="goods-info">
            <div class="goods-name">{{ goods.name }}</div>
            <div class="goods-price">¥{{ goods.price }}</div>
            <div class="goods-stock">库存: {{ goods.stock }}</div>
          </div>
          <div class="quantity-controls" v-if="selectedGoods.some(g => g.id === goods.id)">
            <button @click.stop="decreaseQuantity(goods.id)">-</button>
            <span>{{ getQuantity(goods.id) }}</span>
            <button @click.stop="increaseQuantity(goods.id)">+</button>
          </div>
          <div class="select-indicator" v-if="selectedGoods.some(g => g.id === goods.id)">✓</div>
        </div>
      </div>
    </div>

    <!-- 订单备注 -->
    <div class="remark-section">
      <div class="section-title">订单备注</div>
      <textarea 
        v-model="orderRemark" 
        placeholder="请输入订单备注（可选）"
        class="remark-input"
        maxlength="200"
      ></textarea>
      <div class="char-count">{{ orderRemark.length }}/200</div>
    </div>

    <!-- 订单汇总 -->
    <div class="summary-section">
      <div class="section-title">订单汇总</div>
      <div class="summary-item" v-for="item in selectedGoods" :key="item.id">
        <span class="item-name">{{ item.name }}</span>
        <span class="item-quantity">x{{ item.quantity }}</span>
        <span class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
      </div>
      <div class="total-price">
        <span>总计：</span>
        <span class="price">¥{{ totalPrice.toFixed(2) }}</span>
      </div>
    </div>

    <!-- 提交按钮 -->
    <div class="submit-section">
      <button 
        class="submit-btn" 
        :disabled="!canSubmit || submitting"
        @click="submitOrder"
      >
        {{ submitting ? '提交中...' : '提交订单到队列' }}
      </button>
    </div>

    <!-- 地址编辑弹窗 -->
    <div class="modal-overlay" v-if="showAddressModal" @click="closeAddressModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>编辑收货地址</h3>
          <button class="close-btn" @click="closeAddressModal">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>收货人</label>
            <input v-model="addressForm.name" placeholder="请输入收货人姓名" />
          </div>
          <div class="form-group">
            <label>手机号</label>
            <input v-model="addressForm.phone" placeholder="请输入手机号" />
          </div>
          <div class="form-group">
            <label>详细地址</label>
            <textarea v-model="addressForm.detail" placeholder="请输入详细地址"></textarea>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeAddressModal">取消</button>
          <button class="save-btn" @click="saveAddress">保存</button>
        </div>
      </div>
    </div>

    <!-- 订单状态弹窗 -->
    <div class="modal-overlay" v-if="showOrderStatus" @click="closeOrderStatus">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>订单状态</h3>
          <button class="close-btn" @click="closeOrderStatus">×</button>
        </div>
        <div class="modal-body">
          <div class="order-info">
            <div class="info-item">
              <span class="label">订单号：</span>
              <span class="value">{{ currentOrder.order_no }}</span>
            </div>
            <div class="info-item">
              <span class="label">状态：</span>
              <span class="value status" :class="currentOrder.status">
                {{ getStatusText(currentOrder.status) }}
              </span>
            </div>
            <div class="info-item">
              <span class="label">创建时间：</span>
              <span class="value">{{ formatTime(currentOrder.created_at) }}</span>
            </div>
          </div>
          <div class="status-description">
            <p v-if="currentOrder.status === 'pending'">
              📋 订单已提交到处理队列，正在等待处理...
            </p>
            <p v-else-if="currentOrder.status === 'processing'">
              ⚙️ 订单正在处理中，请稍候...
            </p>
            <p v-else-if="currentOrder.status === 'completed'">
              ✅ 订单处理完成！
            </p>
            <p v-else-if="currentOrder.status === 'failed'">
              ❌ 订单处理失败，请联系客服
            </p>
          </div>
        </div>
        <div class="modal-footer">
          <button class="refresh-btn" @click="refreshOrderStatus">刷新状态</button>
          <button class="close-btn-primary" @click="closeOrderStatus">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import orderService from '@/api/order-fixed'

const router = useRouter()

// 响应式数据
const rabbitMQConnected = ref(false)
const address = ref({ name: '', phone: '', detail: '' })
const addressForm = ref({ name: '', phone: '', detail: '' })
const showAddressModal = ref(false)
const availableGoods = ref([])
const selectedGoods = ref([])
const orderRemark = ref('')
const submitting = ref(false)
const showOrderStatus = ref(false)
const currentOrder = ref({})

// 计算属性
const totalPrice = computed(() => {
  return selectedGoods.value.reduce((total, item) => {
    return total + (item.price * item.quantity)
  }, 0)
})

const canSubmit = computed(() => {
  return selectedGoods.value.length > 0 && 
         address.value.name && 
         address.value.phone && 
         address.value.detail &&
         rabbitMQConnected.value
})

// 方法
const goBack = () => {
  router.go(-1)
}

const testRabbitMQ = async () => {
  try {
    const result = await orderService.testConnection()
    if (result.code === 200) {
      rabbitMQConnected.value = true
      alert('RabbitMQ连接测试成功！')
    } else {
      rabbitMQConnected.value = false
      alert('RabbitMQ连接测试失败：' + result.message)
    }
  } catch (error) {
    rabbitMQConnected.value = false
    alert('RabbitMQ连接测试失败：' + error.message)
  }
}

const loadAvailableGoods = () => {
  // 模拟商品数据，实际应该从API获取
  availableGoods.value = [
    { id: 1, name: '小红书周边T恤', price: 99.00, stock: 50, image_url: '/images/tshirt.jpg' },
    { id: 2, name: '小红书马克杯', price: 39.00, stock: 100, image_url: '/images/mug.jpg' },
    { id: 3, name: '小红书笔记本', price: 29.00, stock: 80, image_url: '/images/notebook.jpg' },
    { id: 4, name: '小红书帆布袋', price: 49.00, stock: 60, image_url: '/images/bag.jpg' }
  ]
}

const toggleGoods = (goods) => {
  const existingIndex = selectedGoods.value.findIndex(g => g.id === goods.id)
  if (existingIndex >= 0) {
    selectedGoods.value.splice(existingIndex, 1)
  } else {
    selectedGoods.value.push({
      ...goods,
      quantity: 1
    })
  }
}

const getQuantity = (goodsId) => {
  const item = selectedGoods.value.find(g => g.id === goodsId)
  return item ? item.quantity : 0
}

const increaseQuantity = (goodsId) => {
  const item = selectedGoods.value.find(g => g.id === goodsId)
  const goods = availableGoods.value.find(g => g.id === goodsId)
  if (item && goods && item.quantity < goods.stock) {
    item.quantity++
  }
}

const decreaseQuantity = (goodsId) => {
  const item = selectedGoods.value.find(g => g.id === goodsId)
  if (item && item.quantity > 1) {
    item.quantity--
  }
}

const editAddress = () => {
  addressForm.value = { ...address.value }
  showAddressModal.value = true
}

const closeAddressModal = () => {
  showAddressModal.value = false
}

const saveAddress = () => {
  address.value = { ...addressForm.value }
  localStorage.setItem('delivery_address', JSON.stringify(address.value))
  showAddressModal.value = false
}

const submitOrder = async () => {
  if (!canSubmit.value) return
  
  submitting.value = true
  
  try {
    // 准备订单数据
    const orderData = {
      goods_ids: selectedGoods.value.map(g => g.id),
      quantities: selectedGoods.value.map(g => g.quantity),
      remark: orderRemark.value || `订单创建于 ${new Date().toLocaleString()}`
    }
    
    console.log('🚀 提交订单到RabbitMQ:', orderData)
    
    // 创建订单
    const result = await orderService.createOrder(orderData)
    
    if (result.code === 200) {
      currentOrder.value = {
        order_no: result.data.order_no,
        status: result.data.status,
        created_at: new Date().toISOString()
      }
      
      // 显示订单状态弹窗
      showOrderStatus.value = true
      
      // 清空选择
      selectedGoods.value = []
      orderRemark.value = ''
      
    } else {
      throw new Error(result.message || '订单创建失败')
    }
    
  } catch (error) {
    console.error('订单提交失败:', error)
    alert('订单提交失败：' + error.message)
  } finally {
    submitting.value = false
  }
}

const closeOrderStatus = () => {
  showOrderStatus.value = false
}

const refreshOrderStatus = async () => {
  if (!currentOrder.value.order_no) return
  
  try {
    const result = await orderService.getOrderStatus(currentOrder.value.order_no)
    if (result.code === 200) {
      currentOrder.value.status = result.data.status
    }
  } catch (error) {
    console.error('刷新订单状态失败:', error)
  }
}

const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成',
    'failed': '处理失败'
  }
  return statusMap[status] || status
}

const formatTime = (timeStr) => {
  return new Date(timeStr).toLocaleString()
}

// 生命周期
onMounted(async () => {
  // 加载保存的地址
  const savedAddress = localStorage.getItem('delivery_address')
  if (savedAddress) {
    try {
      address.value = JSON.parse(savedAddress)
    } catch (e) {
      console.error('解析保存的地址失败:', e)
    }
  }
  
  // 加载商品列表
  loadAvailableGoods()
  
  // 测试RabbitMQ连接
  await testRabbitMQ()
})
</script>

<style scoped>
.create-order-container {
  width: 100vw;
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 80px;
}

.header {
  position: sticky;
  top: 0;
  background: #fff;
  padding: 12px 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #eee;
  z-index: 100;
}

.back-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
}

.title {
  font-weight: 600;
  font-size: 16px;
}

.test-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  font-size: 14px;
}

.status-indicator.connected {
  background: #d4edda;
  color: #155724;
}

.status-indicator.disconnected {
  background: #f8d7da;
  color: #721c24;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.connected .status-dot {
  background: #28a745;
}

.disconnected .status-dot {
  background: #dc3545;
}

.section-title {
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.address-section,
.goods-section,
.remark-section,
.summary-section {
  background: #fff;
  margin: 12px 16px;
  padding: 16px;
  border-radius: 8px;
}

.address-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
}

.name-phone {
  display: flex;
  gap: 12px;
  margin-bottom: 4px;
}

.name {
  font-weight: 600;
}

.phone {
  color: #666;
}

.detail {
  color: #666;
  font-size: 14px;
}

.arrow {
  color: #999;
}

.goods-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.goods-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  border: 1px solid #eee;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  transition: all 0.2s;
}

.goods-item.selected {
  border-color: #007bff;
  background: #f8f9ff;
}

.goods-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  background: #eee;
}

.goods-info {
  flex: 1;
}

.goods-name {
  font-weight: 600;
  margin-bottom: 4px;
}

.goods-price {
  color: #ff4757;
  font-weight: 600;
  margin-bottom: 2px;
}

.goods-stock {
  color: #666;
  font-size: 12px;
}

.quantity-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-controls button {
  width: 28px;
  height: 28px;
  border: 1px solid #ddd;
  background: #fff;
  border-radius: 4px;
  cursor: pointer;
}

.select-indicator {
  position: absolute;
  top: 8px;
  right: 8px;
  color: #007bff;
  font-weight: bold;
}

.remark-input {
  width: 100%;
  min-height: 80px;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  resize: vertical;
  font-family: inherit;
}

.char-count {
  text-align: right;
  color: #666;
  font-size: 12px;
  margin-top: 4px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.summary-item:last-child {
  border-bottom: none;
}

.total-price {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 12px;
  border-top: 2px solid #eee;
  font-weight: 600;
  font-size: 16px;
}

.total-price .price {
  color: #ff4757;
}

.submit-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 16px;
  border-top: 1px solid #eee;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: background 0.2s;
}

.submit-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.submit-btn:not(:disabled):hover {
  background: #0056b3;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
}

.modal-body {
  padding: 16px;
  max-height: 400px;
  overflow-y: auto;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 600;
  color: #333;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: inherit;
}

.form-group textarea {
  min-height: 60px;
  resize: vertical;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px;
  border-top: 1px solid #eee;
}

.cancel-btn,
.save-btn,
.refresh-btn,
.close-btn-primary {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.save-btn,
.close-btn-primary {
  background: #007bff;
  color: white;
  border-color: #007bff;
}

.refresh-btn {
  background: #28a745;
  color: white;
  border-color: #28a745;
}

.order-info {
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: 600;
  color: #333;
}

.value {
  color: #666;
}

.value.status {
  font-weight: 600;
}

.value.status.pending {
  color: #ffc107;
}

.value.status.processing {
  color: #007bff;
}

.value.status.completed {
  color: #28a745;
}

.value.status.failed {
  color: #dc3545;
}

.status-description {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  color: #666;
}

.status-description p {
  margin: 0;
}
</style>
